package com.yinhai.message.core.exception;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;

import com.yinhai.core.app.api.util.ServiceLocator;
import com.yinhai.message.api.bean.TMUser;
import com.yinhai.message.api.vo.TMMessageVo;
import com.yinhai.message.core.bpo.IMessageBpo;
import com.yinhai.message.core.event.MessageEvent;
import com.yinhai.message.core.po.MessageDetailPo;
import com.yinhai.message.core.po.id.MessageDetailId;
import com.yinhai.message.core.util.IMessageConstant;
/**
 * 消息发送异常处理
 * @author yanglq 2017.3.30
 * @maxp 2017年3月31日10:02:06
 */
public class TMAsyncExceptionHandler extends SimpleAsyncUncaughtExceptionHandler{

	
	private static final Logger LOGGER = LoggerFactory.getLogger(TMAsyncExceptionHandler.class);
	@Override
	public void handleUncaughtException(Throwable ex, Method method, Object... params) {
		ex.printStackTrace();
		LOGGER.info("error message:"+ex.getMessage()+"===="+" method"+method.getName());
		if(params.length>0){
			IMessageBpo messageBpo = (IMessageBpo) ServiceLocator.getService("messageBpo");
			MessageEvent event = (MessageEvent) params[0];
			TMMessageVo vo = event.getMessageVo();
			List<TMUser> list = vo.getUserlist();
			List<MessageDetailPo> poList = new ArrayList<>();
			for(TMUser user: list){
				String appid = user.getAppId();
				String userid = user.getUserId();
				MessageDetailPo statePo = new MessageDetailPo();
				MessageDetailId stateId = new MessageDetailId();
				stateId.setMgid(vo.getMessage().getMgid());
				stateId.setUserid(userid);
				stateId.setSystemid(appid);
				stateId.setSendertype(event.getEventType());
				statePo.setId(stateId);
				statePo.setState(IMessageConstant.MSG_STATE_SEND_FAIL);
				statePo.setErrorinfo(ex.getMessage());
				poList.add(statePo);
//				messageBpo.modifyMessageSate(statePo);
			}
			messageBpo.modifyMessageSateBatch(poList);
		}
	}

}
